<template>
  <div class="fd-main-box" v-loading.fullscreen="loading">
    <!-- 检索区域 -->
    <div class="search-area">
      <div class="search-item">
        <a-input
          :style="{ minWidth: '320px' }"
          v-model:model-value="flowName"
          placeholder="请输入模型名称搜索"
          allow-clear
          :max-length="16"
        >
          <template #prefix> <icon-search /> </template>
        </a-input>
      </div>
      <div class="btns">
        <a-button type="primary" @click="onFlowCreate()">
          创建模型
          <template #icon> <icon-plus /> </template>
        </a-button>
      </div>
    </div>

    <!-- 流程列表区域 -->
    <div class="flow-groups-area">
      <a-card
        class="empty-flow-box general-card"
        v-if="!flowList || flowList.length == 0"
      >
        <a-empty />
      </a-card>
      <template v-else v-for="group in filteredFlowGroups" :key="group.id">
        <div class="group-item-box">
          <div class="group-header">
            <div class="name">
              <editable-text
                v-model:value="group.name"
                @change="onGroupNameChange($event, group)"
                :hoverable="true"
              />
            </div>
            <div class="operaion">
              <a-popconfirm
                v-if="!group.modelList || group.modelList.length == 0"
                type="warning"
                content="确认删除该分组 ?"
                position="tr"
                @ok="onDeleteGroupClick(group)"
              >
                <a-button size="small">
                  <template #icon><icon-delete :size="18" /> </template>
                </a-button>
              </a-popconfirm>
            </div>
          </div>
          <div class="group-body">
            <div
              class="flow-item"
              v-for="(item, index) in group.modelList"
              :key="index"
            >
              <div class="name-icon flow-item-field">
                <flow-icon :icon="item.icon" :size="40"></flow-icon>
                <div class="name-desc">
                  <span>{{ item.name }}</span>
                  <span class="desc">{{ item.describe }}</span>
                </div>
                <div class="tag">
                  <a-tag color="red" v-if="item.modelStatus == 'STOP'"
                    >已停用</a-tag
                  >
                </div>
              </div>
              <div class="version flow-item-field">
                <a-tag color="arcoblue">{{ `v${item.version}` }}</a-tag>
              </div>
              <div class="form-key flow-item-field">
                表单：<a href="javascript:;" @click="formPreview(item)">
                  {{ item.formName }}
                </a>
              </div>
              <div class="seeable flow-item-field">
                <template v-if="formatPermission(item).type == 0"
                  >全员可见</template
                >
                <template v-if="formatPermission(item).type == 1">
                  <a-tooltip
                    :content="
                      formatFlowInitiator(formatPermission(item).flowInitiators)
                    "
                  >
                    <span>{{
                      formatFlowInitiator(formatPermission(item).flowInitiators)
                    }}</span>
                  </a-tooltip>
                </template>
                <template v-if="formatPermission(item).type == 2"
                  >均不可见</template
                >
              </div>
              <div class="user-name flow-item-field">
                <flow-node-avatar
                  :size="20"
                  :name="item.creatorName || 'xxx'"
                ></flow-node-avatar>
              </div>
              <!-- <div class="time flow-item-field">{{ item.createTime }}</div> -->
              <div class="operations flow-item-field">
                <a-popconfirm
                  type="success"
                  content=" 确定部署该流程?"
                  @ok="onFlowDeploy(item)"
                  position="tr"
                >
                  <a-button size="small">
                    <template #icon>
                      <icon-play-arrow-fill />
                    </template>
                    部署
                  </a-button>
                </a-popconfirm>
                <a-tooltip content="复制">
                  <a-button size="small" @click="onFlowCopy(item)">
                    <template #icon> <icon-copy :size="18" /> </template>
                  </a-button>
                </a-tooltip>
                <a-tooltip content="编辑">
                  <a-button size="small" @click="onFlowEdit(item)">
                    <template #icon> <icon-edit :size="18" /> </template>
                  </a-button>
                </a-tooltip>
                <a-popconfirm
                  v-if="item.modelStatus != 'STOP'"
                  type="warning"
                  content="确认停用该流程 ?"
                  @ok="onFlowFreeze(item, group)"
                  position="tr"
                >
                  <a-button size="small">
                    <template #icon> <icon-stop :size="18" /> </template>
                  </a-button>
                </a-popconfirm>
                <a-popconfirm
                  v-else
                  type="success"
                  content="确认启用该流程 ?"
                  @ok="onFlowEnabled(item, group)"
                  position="tr"
                >
                  <a-button size="small">
                    <template #icon>
                      <icon-check-circle :size="18" />
                    </template>
                  </a-button>
                </a-popconfirm>
                <a-tooltip content="删除">
                  <a-popconfirm
                    type="error"
                    content="确认删除该流程 ?"
                    @ok="onFlowDelete(item, group)"
                    position="tr"
                  >
                    <a-button
                      :disabled="item.isUsed ? true : false"
                      size="small"
                    >
                      <template #icon> <icon-delete :size="18" /> </template>
                    </a-button>
                  </a-popconfirm>
                </a-tooltip>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>

    <flow-group-edit
      ref="groupModel"
      v-model:group="group"
      @ok="onGroupAdded($event)"
    ></flow-group-edit>

    <!-- 置顶 -->
    <back-to-top target-container=".flow-groups-area"></back-to-top>

    <!-- 复制模型 -->
    <FlowModelCopy
      ref="copyModel"
      v-model:modal="copy"
      @ok="onModelCopyed($event)"
    />

    <!-- 预览表单 -->
    <preview-modal ref="previewModal" v-model:modal="form"></preview-modal>
  </div>
</template>

<script setup>
import { onBeforeMount, onMounted, ref, computed } from "vue";
import { useFlowStore, useUserStore, useOrganStore } from "@/stores";
import { useRouter } from "vue-router";
import { Notification } from "@arco-design/web-vue";
import ObjectUtil from "@/components/flow/common/ObjectUtil";
import FlowManApi from "@/api/FlowManApi";
import OrganApi from "@/api/OrganApi";
import EditableText from "@/components/common/EditableText.vue";
import ArrayUtil from "@/components/flow/common/ArrayUtil";
import FlowIcon from "@/components/icons/FlowIcon.vue";
import FlowGroupEdit from "./flow-gorup-edit.vue";
import FlowModelCopy from "./flow-model-copy.vue";
import FlowNodeAvatar from "@/components/common/FlowNodeAvatar.vue";
import {
  IconSearch,
  IconPlus,
  IconDelete,
  IconEdit,
  IconStop,
  IconCheckCircle,
  IconPlayArrowFill,
  IconCopy,
} from "@arco-design/web-vue/es/icon";
import BackToTop from "@/components/common/BackToTop.vue";

import formatDef from "@/components/flow/common/formatDef.js";
import PreviewModal from "../form/preview.vue";

const router = useRouter();
const flowStore = useFlowStore();
const userStore = useUserStore();
const { getById } = useOrganStore();
const loading = ref(false);

let flowName = ref(""); // 流程名称检索
let flowList = ref([]);
const loadGroupsWithFlow = () => {
  loading.value = true;
  FlowManApi.listGroupsWithFlow({})
    .then((resp) => {
      loading.value = false;
      if (resp.code == 0) {
        flowList.value = resp.data.records || [];
        console.log("--", flowList.value);
      }
    })
    .catch(() => (loading.value = false));
};
// 搜索过滤数组
let filteredFlowGroups = computed(() => {
  return ObjectUtil.copy(flowList.value).filter((group) => {
    let { modelList: flows } = group;
    group.modelList = (flows || []).filter((flow) => {
      return flow.name.indexOf(flowName.value) != -1;
    });
    return flows.length > 0;
  });
});

// 流程发起者格式化
const formatFlowInitiator = (flowInitiators) => {
  return (flowInitiators || [])
    .map((item) => {
      // item.id = item.organId;
      return getById(item.id).name;
    })
    .join("，");
};

const formatPermission = (item) => {
  return item.flowPermission
    ? JSON.parse(item.flowPermission)
    : { type: 0, flowInitiators: [] };
};

// 复制模型
let copy = ref({});
let copyModel = ref();
const onFlowCopy = (row) => {
  copyModel.value.show();
  const data = ObjectUtil.copy(row);
  copy.value = { sourceId: data.id };
};
const onModelCopyed = () => {
  loadGroupsWithFlow();
};

// 分组相关
let group = ref({});
let groupModel = ref();
const onNewFlowBtnClick = () => {
  groupModel.value.show();
};
const onGroupAdded = (group) => {
  groups.value.push(group);
};
const onGroupNameChange = (name, group) => {
  if (!name || name == "") return;
  let oldName = group.name;
  group.name = name;
  FlowManApi.InsertOrUpdateGroup({ id: group.id, name: name }).then((resp) => {
    if (resp.code == 0) {
      loadGroupsWithFlow();
    }
  });
};
const onDeleteGroupClick = (group) => {
  FlowManApi.deleteGroup({ id: group.id }).then((resp) => {
    if (resp.code == 1) {
      ArrayUtil.remove(groups.value, "id", group.id);
    }
  });
};

// 表单预览
let previewModal = ref();
let form = ref({});
const formPreview = (row) => {
  form.value = { id: row.formId };
  previewModal.value.show();
};

// 流程相关
const loadFlowConfig = (flowDefinition, callback) => {
  FlowManApi.getFlowConfig({
    id: flowDefinition.id,
    flowDefId: flowDefinition.id,
  }).then((flowDef) => {
    callback && callback(flowDef);
  });
};
const onFlowCreate = () => {
  let user = userStore.loginUser;
  let flowDef = {
    workFlowDef: {
      name: null,
      icon: "/src/assets/icons/icon_1.png",
      flowAdminIds: [user.id], //管理员
      cancelable: 1,
    },
    nodeConfig: {
      name: "发起",
      type: 0,
      assignees: [{ assigneeTypeEnum: "ALL", assigneeType: 12 }],
    },
    flowPermission: { type: 0 },
  };
  // 初始值设定
  flowStore.setFlowDef(flowDef);
  // flowStore.setFlowGroups(groups.value);
  router.push("/flow/edit");
};
const onFlowEdit = (flowDefinition) => {
  loadFlowConfig(flowDefinition, (resp) => {
    // workFlowDef, flowWidgets, nodeConfig, flowPermission
    formatDef.formatFlowJson(resp);
    // flowStore.setFlowGroups(groups.value);
    router.push("/flow/edit");
  });
};
const onFlowDelete = (flowDefinition, group) => {
  console.log("onFlowDelete", flowDefinition);
  FlowManApi.removeById(flowDefinition).then((resp) => {
    if (resp.code == 0) {
      // ArrayUtil.remove(group.flowDefinitions, "id", flowDefinition.id);
      Notification.success("删除成功");
      loadGroupsWithFlow();
    }
  });
};
const onFlowFreeze = (flowDefinition, group) => {
  FlowManApi.freezeById({ id: flowDefinition.id, modelStatus: "STOP" }).then(
    (resp) => {
      if (resp.code == 0) {
        loadGroupsWithFlow();
      }
    }
  );
};
const onFlowEnabled = (flowDefinition, group) => {
  FlowManApi.freezeById({ id: flowDefinition.id, modelStatus: "NORMAL" }).then(
    (resp) => {
      if (resp.code == 0) {
        loadGroupsWithFlow();
      }
    }
  );
};

// 部署模型
const onFlowDeploy = (row) => {
  console.log("onFlowDeploy", row);
  FlowManApi.deployFlowById(row).then((resp) => {
    if (resp.code == 0) {
      Notification.success(`${row.name}部署成功`);
    }
  });
};

onMounted(() => {});

onBeforeMount(() => {
  OrganApi.loadOrgan(); // 加载用户、角色、机构
  loadGroupsWithFlow();
});
</script>

<style scoped lang="less">
@import "@/styles/variables.module.less";

@SearchHeight: 55px;

.fd-main-box {
  user-select: none;
  width: 100%;
  height: calc(100vh - @AppHeaderHeight - @AppBreadcrumbHeight);
  // overflow: hidden auto;
  // overflow: hidden;
  // padding: 0 @Gap;

  .search-area {
    display: flex;
    justify-content: space-between;
    margin: 0 @LayoutGap @LayoutGap;
    border-radius: @BorderRadius;
    height: @SearchHeight;
    padding: 0 @Gap;
    background: #fff;
    display: flex;
    align-items: center;

    button {
      + button {
        margin-left: 10px;
      }
    }
  }

  .flow-groups-area {
    height: calc(
      100vh - @AppHeaderHeight - @AppBreadcrumbHeight - @SearchHeight -
        @LayoutGap
    );
    overflow: hidden auto;
    padding: 0 @LayoutGap;

    .empty-flow-box {
      border-radius: @BorderRadius;
      padding: 48px;
      background-color: #fff;
      border: 0;
    }

    .group-item-box {
      border-radius: @BorderRadius;
      // box-shadow: 0 0 3px 1px #eee;
      background-color: #fff;
      overflow: hidden;
      margin-bottom: @LayoutGap;

      .group-header {
        height: 48px;
        color: var(--color-text-2);
        background-color: #fafafa;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 @Gap;
        // border-bottom: 1px solid #efefef;
      }

      .group-body {
        .flow-item {
          padding: 10px @Gap;
          display: flex;
          align-items: center;
          border-top: 1px solid var(--color-neutral-2);
          transition: all 0.2s;
          gap: 10px;

          //   &:hover {
          //     background-color: #ededee;
          //   }

          .name-icon {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 10px;

            .name-desc {
              display: flex;
              flex-direction: column;
              justify-content: center;
              gap: 4px;
              max-width: 400px;
              min-width: 120px;

              .desc {
                font-size: 13px;
                text-overflow: ellipsis;
                overflow: hidden;
                white-space: nowrap;
                color: #8f959e;
                font-weight: 400;
              }
            }
          }

          .time {
            width: 150px;
          }

          .user-name {
            width: 80px;
            text-align: center;
          }

          .version {
            width: 45px;
          }

          .form-key {
            width: 180px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;

            a {
              color: #333;
            }
          }

          .seeable {
            width: 20%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .operations {
            width: 250px;
            display: flex;
            align-items: center;
            justify-content: end;
            gap: 15px;
          }
        }
      }
    }
  }
}
</style>
